﻿using System.Windows;
using System.Windows.Controls;
using System.Collections.Specialized;
using System.Configuration;
using ScanSnap.Domain.JSON;
using ScanSnap.Util;
using System.Net;

namespace ScanSnap
{
    /// <summary>
    /// Interaction logic for LoginPage.xaml
    /// </summary>
    public partial class LoginPage : Page
    {
        private readonly string SERVER_URL = ConfigurationManager.AppSettings["url"];

        public LoginPage()
        {
            InitializeComponent();
        }

        private void SignInButton_Click(object sender, RoutedEventArgs e)
        {
            using (WebClient client = new WebClient())
            {

                NameValueCollection vals = new NameValueCollection();
                vals.Add("user.email", UsernameText.Text);
                vals.Add("user.userPassword", PasswordText.Password);

                SignInJSON signIn;
                try
                {
                    string resourceUrl = "/user/clientSignIn.html";
                    signIn = JsonReader.JsonDeserialize<SignInJSON>(SERVER_URL + resourceUrl, "POST", vals);
                    if (signIn.Status.Equals("SUCCESS"))
                    {
                        ModelWindow MainApplicationWindow =  new ModelWindow(signIn.User);
                        MainApplicationWindow.Show();
                        
                    }
                    else
                    {
                        ErrorLabel.Content = "ユーザ名とパスワードが無効です。";
                    }
                }
                catch (WebException we)
                {
                    ErrorLabel.Content = "Cannot connect to the server, try again...";
                }
            }
        }
    }
}
